package com.heima.Serivce.impl;

import com.heima.Config.ThreadUtil;
import com.heima.model.ES.Dotos.HistorySearchDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.pojos.ApAssociateWords;
import com.heima.pojos.ApUserSearch;
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MongoService implements com.heima.Serivce.MongoService {
    @Autowired
    MongoTemplate mongoTemplate;


    @Override
    @Async
    public void Save(Integer UserId, String keyword) {
//        查询数据是否存在
        ApUserSearch userSearch = mongoTemplate.findOne(
                Query.query(Criteria.where("userId").is(UserId).and("keyword").is(keyword)),
                ApUserSearch.class);

        if(userSearch!=null)
        {
//        存在，更新搜索记录时间
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
        }
        else
        {
//        不存在
            Query query=Query.query(Criteria.where("userId").is(UserId))
                    .with(Sort.by(Sort.Direction.DESC,"createdTime"));
            List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
            ApUserSearch apUserSearch=new ApUserSearch();
            apUserSearch.setUserId(UserId);
            apUserSearch.setKeyword(keyword);
            apUserSearch.setCreatedTime(new Date());
//        查询用户搜索记录数是否超过5条
            if(apUserSearches.size()<=5||apUserSearches==null)
            {
                //        不超过，直接添加
                mongoTemplate.save(apUserSearch);
            }
            else
            {
                //        超过5条，替换最久的那条
                ApUserSearch temp = apUserSearches.get(apUserSearches.size() - 1);
                mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(temp.getId())),apUserSearch);
            }
        }
    }

    @Override
    public ResponseResult GetSelectHistory() {
        Integer userid= ThreadUtil.Getthread().getId();
        if (userid==null)
            return ResponseResult.errorResult(404,"数据不存在");

        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria.where("userId").is(userid)),
                ApUserSearch.class);
        return ResponseResult.okResult(userSearchList);
    }

    @Override
    public ResponseResult DeleteById(HistorySearchDto historySearchDto) {
        DeleteResult id = mongoTemplate.remove(Query.query(Criteria.where("id").is(historySearchDto.getId()))
                , ApUserSearch.class);
        return ResponseResult.okResult(id);
    }
}
